import Vue from 'vue'
import Vuex from 'vuex'

import $H from '../common/request.js';
import $C from '../common/config.js';
import io from '../common/uni-socket.io.js';

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		user: null,
		token: null,
		socket: null
	},
	actions: {
		login({ state, dispatch }, user) {
			state.user = user
			state.token = user.token
			
			uni.setStorageSync('user', JSON.stringify(user))
			uni.setStorageSync('token', token)
			dispatch('connectSocket')
		},
		getUserInfo({ state }) {
			$H.get('/user/info', {
				token: true,
				noJump: true,
				toast: false
			}).then(res => {
				state.user = res
				uni.setStorage({
					key: "user",
					data: JSON.stringify(state.user)
				})
			})
		},
		logout({ state, dispatch }) {
			$H.post('/logout',{}, {
				token: true,
				toast: false
			})
			dispatch('closeSocket')
			state.user = null
			state.token = null
			uni.removeStorageSync('user')
			uni.removeStorageSync('token')
		},
		initUser({ state }) {
			let u = uni.getStorageSync('user')
			let t = uni.getStorageSync('token')
			if (u) {
				state.user = JSON.parse(u)
				state.token = t
			}
		},
		authMethod({ state }, callback) {
			if (!state.token) {
				uni.showToast({
					title: '请先登录'
				});
				return uni.navigateTo({
					url: '/pages/user/login'
				});
			}
			callback()
		},
		closeSocket({ state,dispatch }) {
			if(state.socket){
				state.socket.close()
			}
		},
		connectSocket({ state,dispatch }) {
			const S = io($C.socketUrl, {
				query: {},
				transports: ['websocket'],
				timeout: 5000
			})
			let onliveEvent = (e) => {
				uni.$emit('live', {
					type: "online",
					data: e
				})
			}
			let commentEvent = (e) => {
				uni.$emit('live', {
					type: "comment",
					data: e
				})
			}
			let giftEvent = (e) => {
				uni.$emit('live', {
					type: "gift",
					data: e
				})
			}
			S.on('connect', () => {
				console.log('已连接')
				state.socket = S
				const { id } = S
				S.on(id, (e) => {
					console.log(e)
					let d = e.data
					if (d.action === 'error') {
						let msg = d.payload
						if (e.meta.notoast) {
							return
						}
						return uni.showToast({
							title: msg
						});
					}
				})
				S.on('online', onliveEvent)
				
				S.on('comment', commentEvent)
				
				S.on('gift', giftEvent)
			})
			const removeListener = () => {
				if (S) {
					S.removeListener('online', onliveEvent)
					S.removeListener('comment', commentEvent)
					S.removeListener('gift', giftEvent)
				}
			}
			S.on('error', () => {
				console.log('连接失败')
				removeListener()
				state.socket = null
			})
			S.on('disconnect', () => {
				console.log('连接断开')
				removeListener()
				state.socket = null
			})
		}
	}
})